#!/usr/bin/env python
# coding=utf-8
import os
import sys
import sys
import time
import datetime
import config
sys.path.append(config.QB_GUI_PATH)
sys.path.append(config.QB_PATH)
# import qbMySQL
from qb_database_ import QubeDatabase
import smtplib
# import os.path
from email.mime.text import MIMEText
import qb
# import nslMsgAccount


def pasted_time(t):
    if t == '':
        return ''
    s = t % 60
    m = t / 60 % 60
    h = t / 3600
    return '%02d:%02d:%02d' % (h, m, s)


def set_and_add(target_dict,key,value):
    if key not in target_dict :
        target_dict[key] = ''
    target_dict[key] += value


def auto_email(target_dict):
    for key in target_dict.keys():
        msg_to = ['%s@base-fx.com'%key]
        msg_Cc = ['chenqx@base-fx.com','haojw@base-fx.com','pranjan@base-fx.com', 'xuxx@base-fx.com','liuying1@base-fx.com']
        # SendText_1 = 'Hi~,%s \n'%key
        # SendText_2 = 'You have some job in the Qube is timeout :\n'
        # SendText_6 = '你有下面这些任务超时渲染 : \n\n'
        # SendText_3 = target_dict[key]
        # SendText_4 = '\nPlease check it ,In general the job you submit will not running more than 14 hours , Thanks'
        # SendText_5 = '\n您的任务超时了，检查一下吧，不然我很可能就失手灭掉他了。'
        # SendText = SendText_1 + SendText_2 + SendText_6 + SendText_3 + SendText_4 + SendText_5
        SendText = '''<html lang="en">
<head></head>
<body>
    <h1>Hello~,%s:</h1>
    <p><b>You have a Task Timeout Alert :</b></p>
    <p><b><font color="#FF0000">%s</font></b></p>
    <p><b>In general the job you submit, will not running more than 14 hours . If you are in special ,please email us. Thanks .</b></p>
    <p><b>您的任务超时了，如有特殊情况请邮件我们，不然Qube很可能就失手灭掉这些任务哦。</b></p>
</body>
</html>'''%(key,target_dict[key])

        # msg = MIMEText(SendText,'plain','utf-8')
        msg = MIMEText(SendText, 'html', 'utf-8')
        msg['From'] = 'chenqx@base-fx.com'
        msg['To'] = ','.join(msg_to)
        msg['Cc'] = ','.join(msg_Cc)
        msg['Subject'] = 'Render Timeout Alert'

        try:
            server = smtplib.SMTP()
            server.connect('imap.base-fx.com')
            server.login('chenqx@base-fx.com', '587hh*12')
            server.sendmail(msg['From'], msg['To'].split(',') + msg['Cc'].split(','),msg.as_string())
            server.quit()
            print 'send email is ok'
        except smtplib.SMTPException:
            print 'Do not send email'
#
# def auto_email_2(target_dict):
#     for key in target_dict.keys():
#         msg_to = ['%s@base-fx.com'%key,'chenqx@base-fx.com']
#         msg_Cc = ['haojw@base-fx.com']
#         SendText_1 = 'Hi~,%s \n'%key
#         SendText_2 = 'You have some job in the Qube is timeout and it retry again:\n'
#         SendText_6 = '你有下面这些任务超时渲染并且重新渲染: \n\n'
#         SendText_3 = target_dict[key]
#         SendText = SendText_1 + SendText_2 + SendText_6 + SendText_3
#
#
#         msg = MIMEText(SendText,'plain','utf-8')
#         msg['From'] = 'chenqx@base-fx.com'
#         msg['To'] = ','.join(msg_to)
#         msg['Cc'] = ','.join(msg_Cc)
#         msg['Subject'] = 'Render farm : retry'
#
#         try:
#             server = smtplib.SMTP()
#             server.connect('imap.base-fx.com')
#             server.login('chenqx@base-fx.com', '587hh*12')
#             server.sendmail(msg['From'], msg['To'].split(',') + msg['Cc'].split(','),msg.as_string())
#             server.quit()
#             print 'send retry email is ok'
#         except smtplib.SMTPException:
#             print 'Do not retry send email'


def main():
    job_send_dict = {}
    # job_send_dict_2 = {}
    q = QubeDatabase()
    job_info = q.time_out(query='where status = 336')
    Ka = 'Katana'
    Nu = 'Nuke'
    count = 0
    for item in job_info:
        jobid = item[0]
        job_pid = q.job_agenda(jobid,'id, name, status, timestart, timecomplete, host')
        for item_pid in job_pid:
            if item_pid[4] == 0L and item_pid[2] == 336:
                now = datetime.datetime.now()
                time_star = datetime.datetime.fromtimestamp(item_pid[3] + config.QUBE_TIME)
                time_use = (now - time_star).total_seconds()
                if time_use >= 43200 and (('MR' in item[3]) or ('AU' in item[3])):
                    time_out = pasted_time(time_use)
                    pid = '<font color="#000000">QUBE_JOB_ID :</font> %s   &nbsp &nbsp     <font color="#000000">Frame :</font> %s   &nbsp &nbsp    <font color="#000000">TIMEOUT :</font> %s    &nbsp &nbsp     <font color="#000000">The_job_name :</font>  %s  <br>' % (item[0], item_pid[1], time_out, item[3])
                    set_and_add(job_send_dict,item[1],pid)
                if time_use >= 7200 and (('MATE' in item[3]) or ('Nuke' in item[3]) or ('DEEP' in item[3]) or ('DATA' in item[3])):
                    time_out = pasted_time(time_use)
                    # block = qb.blockwork('%s:%s' % (item[0], item_pid[1]))
                    # print '-------------block------->',block
                    pid = '<font color="#000000">QUBE_JOB_ID :</font> %s   &nbsp &nbsp     <font color="#000000">Frame :</font> %s   &nbsp &nbsp    <font color="#000000">TIMEOUT :</font> %s    &nbsp &nbsp     <font color="#000000">The_job_name :</font>  %s  <br>' % (item[0], item_pid[1], time_out, item[3])
                    # time.sleep(5)
                    # print '-------------unblock_frame------->', qb.unblockwork('%s:%s' % (item[0], item_pid[1]))
                    # time.sleep(5)
                    # print '-------------unblock_host------->', qb.unblock('%s' % item[0])
                    set_and_add(job_send_dict,item[1],pid)
                if time_use >= 50400 and(('BTY' in item[3]) or ('VOL' in item[3])):

                    time_out = pasted_time(time_use)
                    #block = qb.blockwork('%s:%s' % (item[0], item_pid[1]))
                    #print '-------------block------->', block
                    pid = '<font color="#000000">QUBE_JOB_ID :</font> %s   &nbsp &nbsp     <font color="#000000">Frame :</font> %s   &nbsp &nbsp    <font color="#000000">TIMEOUT :</font> %s    &nbsp &nbsp     <font color="#000000">The_job_name :</font>  %s  <br>' % (item[0], item_pid[1], time_out, item[3])
                    time.sleep(5)
                    #print '-------------unblock_frame------->', qb.unblockwork('%s:%s' % (item[0], item_pid[1]))
                    time.sleep(10)
                    #print '-------------unblock_host------->', qb.unblock('%s' % item[0])
                    set_and_add(job_send_dict, item[1], pid)

    auto_email(job_send_dict)
    # auto_email_2(job_send_dict_2)
    print job_send_dict.keys()
#    print job_send_dict_2.keys()


if __name__ == '__main__':
    starttime = datetime.datetime(2019, 3, 27, 0, 0, 0)
    while datetime.datetime.now() < starttime:
        time.sleep(1)
    print 'start'
    i = 0
    while True:
        main()
        i += 1
        print 'the %sth time to look timeout' % i
        time.sleep(14400)



